package cn.bonoon.kernel.bytecode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;

import cn.bonoon.entities.plugins.ConfigEntity;
import cn.bonoon.kernel.VisibleScope;
import cn.bonoon.kernel.events.BaseEvent;

public class ConfigHandler {
	
	private final static String 
		qlsetter  = "select x from ConfigEntity x where x.type=? and x.oid=? and x.uid=?",
		qlgetter  = "select x.key,x.value from ConfigEntity x where x.type=? and x.oid=? and x.uid=?",
		qlchecker = "select count(x) from ConfigEntity x where x.type=? and x.key=? and x.value and x.oid<>? and x.uid<>?";

	private final EntityManager manager;
	private final String type;
	private final long owner;
	private final long user;
	public ConfigHandler(EntityManager manager, BaseEvent event, String type){
		this.manager = manager;
		this.type = type;
		VisibleScope vs = event.getScope();
		if(vs == VisibleScope.GLOBAL){
			owner = 0;
			user = 0;
		}else{ 
			owner = event.toOwnerId();
			if(vs == VisibleScope.DOMAIN){
				user = 0;
			}else{
				user = event.getId();
			}
		}
	}
	
	public boolean exist(String key, String value){
		return manager.createQuery(qlchecker, Integer.class)
				.setParameter(1, type)
				.setParameter(2, key)
				.setParameter(3, value)
				.setParameter(4, owner)
				.setParameter(5, user)
				.getSingleResult().intValue() > 0;
	}
	
	public List<ConfigEntity> loadEntities(){
		return manager.createQuery(qlsetter, ConfigEntity.class)
				.setParameter(1, type)
				.setParameter(2, owner)
				.setParameter(3, user)
				.getResultList();
	}
	
	public Map<Object, Object> loadMap(){
		Map<Object, Object> map = new HashMap<Object, Object>();
		for(Object it : manager.createQuery(qlgetter)
				.setParameter(1, type)
				.setParameter(2, owner)
				.setParameter(3, user)
				.getResultList()){
			Object[] obj = (Object[])it;
			map.put(obj[0], obj[1]);
		}
		return map;
	}
	
	public void persist(String key, String value){
		ConfigEntity ce = new ConfigEntity();
		ce.setType(type);
		ce.setOid(owner);
		ce.setUid(user);
		ce.setKey(key);
		ce.setValue(value);
		manager.persist(ce);
	}
	
	public void merge(ConfigEntity ce, String key, String value){
		ce.setKey(key);
		ce.setValue(value);
		manager.merge(ce);
	}
}
